package com.example.consumer;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * @author weiZhiLin
 * @version 1.0
 * @date 2021/6/21 16:34
 */
@RestController
public class MainController {
    @Qualifier("eurekaClient")
    @Autowired
    EurekaClient client;

    @Autowired
    LoadBalancerClient lb;


    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/name")
    public String name() {
        return "Im consumer";
    }

    @GetMapping("/getService")
    public String getService() {
        List<InstanceInfo> provider = client.getInstancesByVipAddress("provider", false);
        for (InstanceInfo instanceInfo : provider) {
            System.out.println(ToStringBuilder.reflectionToString(instanceInfo));
        }
        return "Im consumer";
    }

    @GetMapping("/send")
    public String send() {
        List<InstanceInfo> provider = client.getInstancesByVipAddress("provider", false);
        String send = "send";
        if (provider.size() > 0) {
            int index = new Random().nextInt(provider.size());
            InstanceInfo instanceInfo = provider.get(index);
            if (InstanceInfo.InstanceStatus.UP.equals(instanceInfo.getStatus())) {
                String url = "http://" + instanceInfo.getHostName() + ":" + instanceInfo.getPort() + "/getPort";
                RestTemplate restTemplate = new RestTemplate();
                System.out.println(url);
                System.out.println(provider.size());
                String forObject = restTemplate.getForObject(url, String.class);
                send += "-" + index + ":" + forObject;
            }
        }
        return send;
    }

    @GetMapping("/lbSend")
    public String lbSend() {
        ServiceInstance provider = lb.choose("provider");
        String url = "http://" + provider.getHost() + ":" + provider.getPort() + "/getPort";
        restTemplate.getForObject(url, String.class);
        return "forObject";
    }

    @GetMapping("/nameSend")
    public String nameSend() {
        String url = "http://provider/getPort";
        String forObject = restTemplate.getForObject(url, String.class);
        return forObject;
    }
}
